import React from 'react';
import { inject, observer } from 'mobx-react';
import {Button, Row, Col,Spin} from 'antd';
import {WeaTop,WeaDialog,WeaFormItem,WeaLocaleProvider,WeaTools } from 'ecCom';
import * as FnaButton from '../public/FnaButton'
import * as FnaMessage from '../public/FnaMessage'
import {openWorkFlow} from '../util/pulic-func';
import RecognitionModal from './fnaInvoiceIdentify/RecognitionModal';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;


/**
 * 审批助手元素
 */
// @inject('fnaInvoiceIdentifyStore')
@observer
class FnaInvoiceIdentify extends React.Component {
	constructor(props) {
		super(props);
        this.state = {
            list: [],
            upStatus: ''
        };
    }
    
    componentWillMount(){
        const {fnaInvoiceIdentifyStore} = this.props;
		const { getToken } = fnaInvoiceIdentifyStore;

		getToken();
    }

	componentDidMount() {

	}

	componentWillUnmount() {
		//组件卸载时一般清理一些状态
      
	}

	render() {
        const {fnaInvoiceIdentifyStore,commonParam,symbol} = this.props;
        const { hasRight,errorInfo,recognitionVisible,setRecognitionVisible } = fnaInvoiceIdentifyStore;
        let title = getLabel(512309,'发票识别');
        let onOff = false;

        if(recognitionVisible){
            if(hasRight === 1){
                onOff = 1;
            }else if(hasRight === 2){
                onOff = 2;
            }else if(hasRight === 4){
                onOff = 4;
            }else if(hasRight === ''){
                onOff = '';
            }
        }

		return (
			<div style={{height: '100%'}}>
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@izzu2v`} onClick={()=>this.show(symbol)} type='primary'>{title}</Button>
			  	{onOff === 1 && <Ec_FnaInvoiceIdentify ecId={`${this && this.props && this.props.ecId || ''}_Ec_FnaInvoiceIdentify@z7zbyi`} fnaInvoiceIdentifyStore={fnaInvoiceIdentifyStore}  baseParam={commonParam} symbol={fnaInvoiceIdentifyStore.currentBtn} setRecognitionVisible={setRecognitionVisible} backFu={this.backFu}/>}
				{onOff === 2 && <Cloud_FnaInvoiceIdentify ecId={`${this && this.props && this.props.ecId || ''}_Cloud_FnaInvoiceIdentify@wfl3eo`} fnaInvoiceIdentifyStore={fnaInvoiceIdentifyStore} baseParam={commonParam} symbol={fnaInvoiceIdentifyStore.currentBtn} setRecognitionVisible={setRecognitionVisible} backFu={this.backFu} />}
                {onOff === 4 && FnaMessage.fnaWarning(getLabel(2012,'对不起，您暂时没有权限！'))}
                {onOff === '' && <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@5yl5db`} spinning={true}></Spin>}
			</div>
		)
    }

    show = (symbol) =>{
        const { fnaInvoiceIdentifyStore } = this.props;
        const { setRecognitionVisible,setCurrentBtn } = fnaInvoiceIdentifyStore;
        setRecognitionVisible(true);
        setCurrentBtn(symbol);
    }

    backFu = (invoiceIdArr) => {
        const { fnaInvoiceIdentifyStore, commonParam:baseParam,symbol } = this.props;
        const { addDetail, fieldId, setRecognitionVisible } = fnaInvoiceIdentifyStore;
        let dindex = symbol;
        let workflowid = baseParam.workflowid;

        if(symbol == 'main'){
            let invoiceid = window.WfForm.getFieldValue("field" + fieldId);
            let sub = invoiceIdArr.indexOf(parseInt(invoiceid));
            if (sub > -1) {
                invoiceIdArr.splice(sub,1);
            }

        }else{
            let rowIndex = this.getWfRowIndex(dindex);
            let arr = [];
            for (let i = 0; i < invoiceIdArr.length; i++) {
                let rowIndex_array = rowIndex.split(",");
                for (let rowIdx = 0; rowIdx < rowIndex_array.length; rowIdx++) {
                    let idx = rowIndex_array[rowIdx];
                    let invoiceid = window.WfForm.getFieldValue("field" + fieldId + "_" + idx);
                    let sub = invoiceIdArr.indexOf(parseInt(invoiceid));
                    if (sub > -1) {
                        invoiceIdArr.splice(sub,1);
                    }
                    
                }
            }
    
            
        }

        if (invoiceIdArr.length == 0) {
            setRecognitionVisible(false)
            return
        }


        if (dindex == "main") {
            dindex = 0;
        } else {
            dindex = parseInt(dindex.split("_")[1]);
        }
        let params = {
            invoiceIds: invoiceIdArr,
            dindex: dindex,
            workflowid: workflowid,
            operate: "addDetail"
        };

        addDetail(params,(value)=>{
            let desc = value.desc;
            let invoiceInfo = value.invoiceInfo;
            let {fieldindex,fieldIdDate,fieldIdSubject,fieldIdAmount,fieldIdInvoice,fieldIdDesc} = invoiceInfo;
    
            if(invoiceInfo.fieldindex == 0){//主表
                let specialobj = JSON.parse(invoiceInfo.specialobj);
                window.WfForm.changeFieldValue("field"+fieldIdInvoice, {
                    value: invoiceInfo.idStr,
                    specialobj:specialobj
                  });//发票
                //   fieldIdSubject && window.WfForm.changeFieldValue("field"+fieldIdSubject, {value:subjectName});//科目
                //   fieldIdAmount && window.WfForm.changeFieldValue("field"+fieldIdAmount, {value:taxIncludedPrice});//金额
                //   fieldIdDate && window.WfForm.changeFieldValue("field"+fieldIdDate, {value:billingDate});//日期
                //   fieldIdDesc && window.WfForm.changeFieldValue("field"+fieldIdDesc, {value:invoiceServiceYype});//说明
            }else{
                for(let i = 0;i<desc.length;i++){
                    window.WfForm.setDetailAddUseCopy(symbol, false);
                    let detail = "detail_"+fieldindex;
                    let addDetailRow_paramObj = {};
                    addDetailRow_paramObj["field"+fieldIdInvoice] = {value : desc[i].id , specialobj : [{id : desc[i].id, name : desc[i].invoiceNumber}]};//发票
                    if(fieldIdSubject>0){
                      addDetailRow_paramObj["field"+fieldIdSubject] = {value : desc[i].subjectId, specialobj : [{id : desc[i].subjectId, name : desc[i].subjectName}]};//科目
                    }
                    if(fieldIdAmount>0){
                        addDetailRow_paramObj["field"+fieldIdAmount] = {value : desc[i].taxIncludedPrice};//金额
                    }
                    if(fieldIdDate>0){
                        addDetailRow_paramObj["field"+fieldIdDate] = {value : desc[i].billingDate};//日期
                    }
                    if(fieldIdDesc>0){
                        addDetailRow_paramObj["field"+fieldIdDesc] = {value : desc[i].invoiceServiceYype};//说明
                    }
                    window.WfForm.addDetailRow(detail,addDetailRow_paramObj);
                }
            }

            this.props.fnaInvoiceIdentifyStore.setLoding(false);
            setRecognitionVisible(false)
        });        

    }

    //获取所有行 标识
    getWfRowIndex = (detail) => {
        let rowIndex = window.WfForm.getDetailAllRowIndexStr(detail);
        return rowIndex;
    }        


}


export default WeaTools.tryCatch(React,
	props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@9hxnij`} msg={ props.error ? props.error : getLabel(385218,'对不起,该页面异常,请联系管理员!')} />,
	{error: ""}
)(FnaInvoiceIdentify);



/**
 * 审批助手元素
 */
@observer
class Ec_FnaInvoiceIdentify extends React.Component {
	constructor(props) {
		super(props);
        this.state = {
            list: [],
            upStatus: '',
        };
    }

	componentDidMount() {
        const {fnaInvoiceIdentifyStore,symbol,baseParam} = this.props;
        const {doSerach,setSelectedRowKeys,getFieldId} = fnaInvoiceIdentifyStore;
        doSerach({reimbursementType:"0"});

        // let _dindex = symbol == 'main' ? 0 : symbol.split('_')[1];
        // getFieldId({
        //     dindex:_dindex,
        //     workflowid:baseParam.workflowid
        // },(data)=>{
        //     if(_dindex == 0){
        //         let _onRowSelectArr = [];
        //         let invoiceid = window.WfForm.getFieldValue("field" + data.fieldId);
        //         invoiceid = invoiceid ? invoiceid.toString() : invoiceid;  
        //         _onRowSelectArr.push(invoiceid);    
        //         setSelectedRowKeys(_onRowSelectArr);
        //     }else{
        //         let rowIndex = window.WfForm.getDetailAllRowIndexStr(symbol);
        //         let rowIndex_array = rowIndex.split(",");
        //         let _onRowSelectArr = [];
        //         for(let rowIdx = 0; rowIdx < rowIndex_array.length; rowIdx++){
        //             let idx = rowIndex_array[rowIdx];
        //             let invoiceid = window.WfForm.getFieldValue("field" + data.fieldId + "_" + idx);
        //             invoiceid = invoiceid ? invoiceid.toString() : invoiceid;               
        //             _onRowSelectArr.push(invoiceid);
        //         }
        //         setSelectedRowKeys(_onRowSelectArr)
        //     }
            

        // })
	}
	
	componentWillReceiveProps(nextProps) {
		
	}

	shouldComponentUpdate(nextProps, nextState) {
		
		return true;
	}

	componentWillUnmount() {
		//组件卸载时一般清理一些状态
	}

	render() {
        const { fnaInvoiceIdentifyStore } = this.props;
        const { loading,recognitionVisible,tableStore, } = fnaInvoiceIdentifyStore;
        let title = getLabel(512309,'发票识别');

		return (
			<div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@dznc8r`}
                    icon='icon-coms-Finance'
                    iconBgcolor='#f14a2d'
                    title={title}
                    visible={recognitionVisible}
                    style={{width:1000,height:550}}
                    maskClosable={false}
                    onCancel={this.handleCancel}
                    buttons={this.getBottomButton()}
                >
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@tjh4zs`} spinning={loading}>
                        {/* {this.getFormData()} */}
                        <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@7b3xjn`}
                            loading={loading}
                            buttons={this.getTopRightButton()}
                            buttonSpace={10}
                            showDropIcon={false}
                        />

                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@9952ql`}
                            comsWeaTableStore={tableStore}
                            tableWidth={this.getTableWidth}
                            hasOrder={true}
                            needScroll={true}
                        />
                    </Spin>
                </WeaDialog>
			</div>
		)
    }

    getTableWidth = (columns) => {
        let showLength = columns.filter((col) => col.display == 'true').length;
        return 13 * showLength + "%";//也支持返回固定值，如果小于100%,不会生效。
    }

    //Top右侧按钮菜单
	getTopRightButton = () => {
		const { fnaInvoiceIdentifyStore } = this.props;
		const { doSerach,loading } = fnaInvoiceIdentifyStore;
		let btns = [];
		btns.push(<RecognitionModal ecId={`${this && this.props && this.props.ecId || ''}_RecognitionModal@nmndwh@recognitionModal`} componentType='invoiceRecognition' refreshInvoiceList={()=>doSerach({reimbursementType:"0"})} loading={loading}/>);

		return btns;
	}

    //获取form
    getFormData = (value) => {
        return  <div>
            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@acxmph`} align={"middle"} className='wea-fna-upload'>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zvw50z`} span={2}></Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ma5xkk`} span={20} style={{marginTop:10}}>
                    <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@z5qmum`}
                        label={getLabel(387236,'发票图片')}
                        labelCol={{span: `6`}}
                        wrapperCol={{span: `18`}}>
                            {this.getImportFileCompoment()}
                            <div style={{color:'red',marginLeft:'45px', position: 'absolute',top: '0px',right: '50px'}}>
                                <div>1. {getLabel(513241,'仅限上传jpg,jpeg,png,pdf格式!')}</div>
                                <div>2. {getLabel(512318,'一次最多添加10张进行识别!')}</div>
                            </div>
                    </WeaFormItem>
                </Col>
            </Row>
        </div>;
    }    
    
    //取消
    handleCancel = () => {
        this.props.setRecognitionVisible(false);
    } 
    
    //右下角点击按钮
    getBottomButton = () => {
        const { loading } = this.props.fnaInvoiceIdentifyStore;
        let buts=[];
        buts.push(FnaButton.getPrimaryButton(this.handleback,loading,getLabel(826,'确定')));
        buts.push(FnaButton.getPrimaryButton(this.handleback,loading,getLabel(31129,'取消')));

        return buts;
    }  
    
    //回写数据
    handleback = () =>{
        const {fnaInvoiceIdentifyStore,backFu} = this.props;
        const {tableStore} = fnaInvoiceIdentifyStore;
        const { selectedRowKeys } = tableStore;
        let keys = mobx.toJS(selectedRowKeys);
        backFu(keys);
    }





}



/*
*   发票云 发票台账
*/
// @inject('fnaInvoiceIdentifyStore')
@observer
class Cloud_FnaInvoiceIdentify extends React.Component {
	constructor(props) {
        super(props);
        this.state = {
            onRowSelectArr: []
        }
    }

    componentWillMount(){
        const { setLoding } = this.props.fnaInvoiceIdentifyStore;
        setLoding(true);
    }

	componentDidMount() {
        const { fnaInvoiceIdentifyStore,symbol,baseParam } = this.props;
        const { getFieldId,getFidOrEcid,setLoding } = fnaInvoiceIdentifyStore;

        let getLoadIframe = new Promise( (resolve, reject) =>{
            let timer = setInterval(()=>{
                let childFrame = document.getElementById("myIframe");
                if(childFrame){
                    childFrame.addEventListener("load", function() {
                        resolve(true)
                    }, false);
    
                    clearInterval(timer);
                    
                }
            },10);
        })

        getLoadIframe.then( res =>{
            if(res){
                setLoding(false);
            }
        })

        // let _dindex = symbol == 'main' ? 0 : symbol.split('_')[1];
        // getFieldId({dindex:_dindex,workflowid:baseParam.workflowid},(data)=>{
        //     if(_dindex == 0){
        //         let _onRowSelectArr = [];
        //         let invoiceid = window.WfForm.getFieldValue("field" + data.fieldId);
        //         invoiceid = invoiceid ? invoiceid.toString() : invoiceid;  
        //         _onRowSelectArr.push(invoiceid);    
        //         getFieldId({invoiceEcIdArray:_onRowSelectArr},(data)=>{
        //             this.setState({onRowSelectArr:data});
        //         })
        //     }else{
        //         let rowIndex = window.WfForm.getDetailAllRowIndexStr(symbol);
        //         let rowIndex_array = rowIndex.split(",");
        //         let _onRowSelectArr = [];
        //         for(let rowIdx = 0; rowIdx < rowIndex_array.length; rowIdx++){
        //             let idx = rowIndex_array[rowIdx];
        //             let invoiceid = window.WfForm.getFieldValue("field" + data.fieldId + "_" + idx);
        //             invoiceid = invoiceid ? invoiceid.toString() : invoiceid;               
        //             _onRowSelectArr.push(invoiceid);
        //         }
                
        //         getFidOrEcid({method:'cloudId',ids:_onRowSelectArr},(data)=>{
        //             this.setState({onRowSelectArr:data.targetIds});
        //         })
        //     }
            

        // })
		window.addEventListener('message',this.receiver,false);
	}
	
	componentWillUnmount() {
        //组件卸载时一般清理一些状态
        let timer = setInterval(()=>{
            if($('#myIframe').length > 0){
                $('#myIframe').remove();
                clearInterval(timer);
            }
        },10);
		window.removeEventListener('message',this.receiver,false)
    }
       

	render() {
        const {fnaInvoiceIdentifyStore} = this.props;
        const {getInvoiceCloudUrl,recognitionVisible,loading} = fnaInvoiceIdentifyStore;

        let comp = JSON.stringify({seq:'fna',name:'SelectInvoice',param: {multi:true,fids:this.state.onRowSelectArr}});
		                                   
		return (
			<div style={{height: '100%'}}>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@qenc0x`}
                    icon='icon-coms-Finance'
                    iconBgcolor='#f14a2d'
                    // title={title}
                    visible={recognitionVisible}
                    style={{width:800,height:500}}
                    maskClosable={false}
                    onCancel={this.handleCancel}
                    // buttons={this.getBottomButton()}
                    className={'fnaInvoiceIdentify'}
                >
                    <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@j3u2dc`} spinning={loading}>
                        <iframe 
                            className='ec-iframe' 
                            src={getInvoiceCloudUrl(0,{comp:encodeURIComponent(comp)})}
                            style={{width:'100%',height:'100%',border:'0'}}
                            id={"myIframe"} 
                        />
                    </Spin>
                </WeaDialog>
			</div>
		)
    }

    //取消
    handleCancel = () => {
        this.props.setRecognitionVisible(false);
    }
    

    //右键菜单
    getRightMenu = () => {
        const { loading } = this.props.fnaInvoiceIdentifyStore;
        let btns = [];

        btns.push({
                key:"save",
                icon: <i className="icon-portal-operation-o" />,
                content:getLabel(512319,'识别'),
                disabled:loading,
                onClick:this.handleSubmit
        });
        
        return btns;
    }  
	
    receiver = (event) =>{
        const securityOriginList = this.props.fnaInvoiceIdentifyStore.securityOriginList;
        if (!securityOriginList.includes(event.origin)) return ;
        let returnData = event.data;
        if(returnData.seq !== 'fna')return;
		console.log('InvoiceLedger ----returnData',returnData);
		
		switch(returnData.type){
            case 'ERROR' :  //token失效
                if(returnData.ret == '-2'){
                    this.sendResult('UPDATE_TOKEN');
                }

                break;   
            case 'retData' :  
                let arr = [];
                returnData.datas.map( items =>{
                    arr.push(items.oa.id);
                })

                arr.length > 0 && this.props.backFu(arr);
                break;   
            case 'close' :  
                this.handleCancel();
                break;   
            case 'flowOpen':
				openWorkFlow(returnData.data.id);
				break;  				
            default :
                break;                    
        }
	}
	
    //发送数据到 iframe
    sendResult = (type,data)=>{
        const {fnaInvoiceIdentifyStore} = this.props;
        const {getToken} = fnaInvoiceIdentifyStore;

        let that = this;
        switch(type){
			case 'UPDATE_TOKEN' :
				getToken({tokenUnusual:1},()=>{
                    that.sendMessage({
                        type: 'UPDATE_TOKEN',
                        token: fnaInvoiceIdentifyStore.invoiceCloudInfo.token
                    });
                })
                break;
			default :
                break;   
        }

    }	

    //统一发送数据
    sendMessage = (data) =>{
        const {invoiceCloudInfo} = this.props.fnaInvoiceIdentifyStore;
        let childFrame = document.getElementById("myIframe");
		let url = invoiceCloudInfo.jsUrl;
		
        console.log('sendMessage----------data',data);
        childFrame.contentWindow.postMessage(data, url); 
    }	
	
}



